package com.lotea.android.andreaditlater.ui.activities;

import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;

import com.lotea.android.andreaditlater.R;
import com.lotea.android.andreaditlater.data.db.DbAdapter;
import com.lotea.android.andreaditlater.io.APIHelper;
import com.lotea.android.andreaditlater.ui.adapters.ItemListAdapter;
import com.lotea.android.andreaditlater.ui.widgets.ItemQuickAction;
import com.lotea.android.andreaditlater.utils.Log;
import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.OnRefreshListener;

public class Main extends ListActivity implements TextWatcher {

	private ImageButton buttonRefresh;
	private ImageButton buttonSearch;
	private EditText etSearch;

	private Context mContext;
	private ItemListAdapter mListAdapter;
	private DbAdapter mDbAdapter;
	

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mContext = this;

		initButtons();
		
		etSearch = (EditText) findViewById(R.id.etSearch);
		etSearch.addTextChangedListener(this);

		mDbAdapter = new DbAdapter(this);
		mDbAdapter.open();
		Cursor cursor = mDbAdapter.queryItems(null, null);
		
		startManagingCursor(cursor);
		mListAdapter = new ItemListAdapter(this, cursor, mDbAdapter);
		setListAdapter(mListAdapter);

		// Set a listener to be invoked when the list should be refreshed.
		((PullToRefreshListView) getListView())
				.setOnRefreshListener(new OnRefreshListener() {
					@Override
					public void onRefresh() {
						// Do work to refresh the list here.
						new LoadData().execute();
					}
				});
		
		// Check whether the activity began because of a search intent
		Intent intent = getIntent();

		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);
			findViewById(R.id.action_bar).setVisibility(View.GONE);
			etSearch.setText(query);
		} else {
			findViewById(R.id.search_bar).setVisibility(View.GONE);
		}
	}

	@Override
	protected void onPause() {
		if (isFinishing()) {
			mDbAdapter.close();
		}
		super.onPause();
	}

	private void initButtons() {
		buttonRefresh = (ImageButton) findViewById(R.id.title_button_left);
		buttonSearch = (ImageButton) findViewById(R.id.title_button_right);

		// Set images
		buttonRefresh.setImageResource(R.drawable.ic_title_refresh_default);
		buttonSearch.setImageResource(R.drawable.ic_title_search_default);

		// OnClickListeners
		buttonRefresh.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				new LoadData().execute();
			}
		});
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.ListActivity#onListItemClick(android.widget.ListView,
	 * android.view.View, int, long)
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Log.i(getClass().getName(), ", itemClick: id = ", Long.toString(id));

		super.onListItemClick(l, v, position, id);
	}

	public void onOptionsClick(View v) {
		View parent = (View) v.getParent();

		ItemQuickAction mBar = new ItemQuickAction(this, (Integer) v.getTag());
		mBar.show(parent);
	}

	private void switchProgressOn() {
		buttonRefresh.setVisibility(View.INVISIBLE);
		buttonRefresh.setClickable(false);

		findViewById(R.id.title_button_left_progress).setVisibility(
				View.VISIBLE);
	}

	private void switchProgressOff() {
		buttonRefresh.setVisibility(View.VISIBLE);
		buttonRefresh.setClickable(true);

		findViewById(R.id.title_button_left_progress).setVisibility(
				View.INVISIBLE);
	}

	private class LoadData extends AsyncTask<Void, Void, Cursor> {
		@Override
		protected void onPreExecute() {
			switchProgressOn();
		}

		@Override
		protected Cursor doInBackground(Void... args) {

			// Get data from the Internet and put it into db
			APIHelper apiHelper = new APIHelper(mContext,
					getString(R.string.api_key));
			apiHelper.getList("username", "password", 0,
					APIHelper.STATE_ALL);

			// Get data from db
			DbAdapter mDbAdapter = new DbAdapter(mContext);
			mDbAdapter.open();
			Cursor cursor = mDbAdapter.queryItems(null, null);
			mDbAdapter.close();
			startManagingCursor(cursor);

			return cursor;
		}

		@Override
		protected void onPostExecute(Cursor cursor) {
			switchProgressOff();

			// Put data from db into the listview
//			mListAdapter = new ItemListAdapter(mContext, cursor);
//			setListAdapter(mListAdapter);
			mListAdapter.getFilter().filter(null);

			// Call onRefreshComplete when the list has been refreshed.
			((PullToRefreshListView) getListView()).onRefreshComplete();

			super.onPostExecute(cursor);
		}
	}

	@Override
	public void afterTextChanged(Editable s) {
		// Do nothing
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// Do nothing
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		mListAdapter.getFilter().filter(s);
	}
}